<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" label-width="80px">
      <el-row style="background-color: #fff;margin-bottom: 20px;border-radius: 8px;box-sizing: border-box;padding: 20px 20px 0;">
        <div class="card-title-wrap">
          <span>车型选择</span>
          <span></span>
        </div>
        <el-form-item label="产品方案车型配置:" label-width="170px">
          <el-radio-group v-model="vicType" v-if="$route.query.type !== 'detail'" @change.once="changeTypeVic">
            <el-radio :label="1">选择适用车型</el-radio>
            <el-radio :label="0">选择不适用车型</el-radio>
          </el-radio-group>
          <span v-if="$route.query.type == 'detail'">{{ $route.query.matchingRelation==1?'选择适用车型':'选择不适用车型' }}</span>
        </el-form-item>
      </el-row>
      <el-row style="background-color: #fff;margin-bottom: 20px;border-radius: 8px;box-sizing: border-box;padding: 20px 20px 0;">
        <div class="card-title-wrap">
          <span>车型信息</span>
          <span></span>
        </div>
        <el-form-item label="选择类型:" style="margin-left: 30px;">
          <el-radio-group v-model="typeRadio" @change="changeType" :disabled="$route.query.type == 'detail'">
            <el-radio :label="1">品牌</el-radio>
            <el-radio :label="2">车系</el-radio>
            <el-radio :label="3">车型</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <div style="position: relative; background-color: #fff;margin-bottom: 20px;border-radius: 8px;box-sizing: border-box;padding: 20px 20px 0;display: flex;justify-content: start;">
        <el-form-item style="width: 20%;" label="品牌:" v-if="typeRadio ==1 || typeRadio ==2 || typeRadio ==3">
          <el-select v-model="queryParams.brandIds" clearable multiple filterable @change="getSeriesName">
            <template v-for="dict in brandList">
              <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="车系:" v-if="typeRadio ==2 || typeRadio ==3" style="width: 25%">
          <el-select v-model="queryParams.seriesIds" clearable multiple filterable @change="getModelName" style="width: 80%;">
            <template v-for="dict in seriesList">
              <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="车型:" v-if="typeRadio == 3" style="width: 42%">
          <el-select v-model="queryParams.modelIds" clearable multiple filterable style="width: 80%;">
            <template v-for="dict in modelList">
              <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <div style="position: absolute;right: 10px;">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click.stop="sure" v-if="$route.query.type == 'add' || $route.query.type == 'edit'">确认</el-button>
          <el-button @click="back" type="primary">返回</el-button>
        </div>
      </div>
    </el-form>
    <div class="card-wrap card-padding">
      <div v-if="$route.query.type == 'detail'" style="margin-bottom: 20px;text-align: right;">
        <!-- <el-button type="primary" @click="deleteTable" :disabled="multipleSelectionBrand.length <= 0">删除</el-button> -->
        <el-button @click="handleExport">导出</el-button>
      </div>
      <!-- {{ multipleSelectionBrand }}----{{ multipleSelectionSeries }}----{{ multipleSelectionModel }} -->
      <table-page ref="el-table" rowKey="indexId" :loading="loading" :isSelect="$route.query.type == 'detail'?false:true" :dataList="typeRadio ==1?brandDataList:typeRadio ==2?seriesDataList:modelDataList" border :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @setSizeCurrent="listData" @selectionChange="handleSelectionChange">
        <!-- 普通列插槽 -->
        <template slot="tableCol">
          <el-table-column label="品牌" align="center" prop="brandName" v-if="typeRadio ==1 || typeRadio ==2 || typeRadio ==3" />
          <el-table-column label="车系" align="center" prop="seriesName" v-if="typeRadio ==2 || typeRadio ==3" />
          <el-table-column label="车型" align="center" prop="modelName" v-if="typeRadio ==3" />
        </template>
      </table-page>
    </div>
  </div>
</template>
<script>
import {
  getQueryModelByIdList,
  getSeriesName,
  getModelName,
  getBrandName,
  updateCarModel,
  getModelCar,
  deleteCar,
  addCarModel,
  querySelectModelId
} from "@/api/globalField";
export default {
  data() {
    return {
      listDataS: [],
      indexIds: [],
      brandList: [],
      seriesList: [],
      modelList: [],
      vicType: 1,
      // 遮罩层
      loading: true,
      total: 0,
      brandDataList: [],
      seriesDataList: [],
      modelDataList: [],
      typeRadio: 1,
      multipleSelectionBrand: [],
      multipleSelectionSeries: [],
      multipleSelectionModel: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  created() {
    this.getName();
    if (this.$route.query.type == "add") {
      this.getList();
    } else if (this.$route.query.type == "edit") {
      this.getList();
      this.querySelectModelId()
    }
    else {
      this.getModelCar();
      this.querySelectModelId()
    }
  },
  watch: {
    listDataS: {
      handler(newVal) {
        console.log(newVal, 'newVal');
        this.$nextTick(() => {
          newVal.forEach((v) => {
            this.indexIds.forEach((j) => {
              if (
                v.indexId == j
              ) {
                this.$refs['el-table'].table_toggleRowSelection(v, true)
              }
            });
          });
        });
      },
      immediate: true, // 立即生效
      deep: true  //监听对象或数组的时候，要用到深度监听
    }
  },
  mounted() {
    this.vicType = this.$route.query.matchingRelation == undefined ? 1 : Number(this.$route.query.matchingRelation)
  },
  dicts: ["energy_type"],
  methods: {
    querySelectModelId() {
      let params = {
        quotationProductSchemeId: this.$route.query.id
      }
      querySelectModelId(params).then(res => {
        console.log(res, '000-0-00000');
        this.typeRadio = res.data.modelType
        this.$set(this.queryParams, "brandIds", res.data.selectBrandIds?.map(String));
        this.queryParams.brandIds && this.getSeriesName()
        this.$set(this.queryParams, "seriesIds", res.data.selectSeriesIds?.map(String))
        this.queryParams.seriesIds && this.getModelName()
        this.$set(this.queryParams, "modelIds", res.data.selectModelIds?.map(String));
        this.indexIds = res.data.indexIds
        this.handleQuery()
      })
    },
    changeTypeVic() {
      if (this.$route.query.type == 'edit') {
        if (this.vicType == 0) {
          this.$confirm('此操会将之前选择的适用车型更改为不适用车型, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$message({
              type: 'success',
              message: '已更改!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
            this.vicType = 1
          });
        }
      }
    },
    changeType() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }
      this.brandList = [];
      this.seriesList = [];
      this.modelList = [];
      this.multipleSelectionBrand = []
      this.multipleSelectionSeries = []
      this.multipleSelectionModel = []
      this.getName()
      this.$refs['el-table'].table_clearSelection()
      if (this.$route.query.type == "add" || this.$route.query.type == "edit") {
        this.getList();
      } else {
        this.getModelCar();
      }
    },
    listData() {
      if (this.$route.query.type == "add" || this.$route.query.type == "edit") {
        this.getList();
      } else {
        this.getModelCar();
      }
    },
    // 详情的时候调取接口
    getModelCar() {
      this.loading = true;
      this.queryParams = {
        ...this.queryParams,
        quotationProductSchemeId: this.$route.query.id,
        modelType: this.typeRadio,
        queryType: 1
      };
      getModelCar(this.queryParams).then((res) => {
        if (res.code == "200") {
          this.loading = false;
          const { rows, total } = res;
          this.brandDataList = rows;
          this.seriesDataList = rows;
          this.modelDataList = rows;
          this.total = total;
          this.loading = false;
        }
      });
    },
    deleteTable() {
      this.$confirm("确认删除?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteCar({
            quotationProductSchemeId: this.$route.query.id,
            carModelIdList: this.multipleSelectionBrand,
          }).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.multipleSelectionBrand = [];
            this.getModelCar();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download_json(
        "quoter/scheme/carModel/export",
        {
          quotationProductSchemeId: this.$route.query.id,
          brandIds: this.queryParams.brandIds,
          seriesIds: this.queryParams.seriesIds,
          modelIds: this.queryParams.modelIds,
          modelType: this.typeRadio,
        },
        `所选车型表_${new Date().getTime()}.xlsx`
      );
    },
    getName() {
      getBrandName([]).then((res) => {
        this.brandList = res;
      });
    },
    getSeriesName() {
      if (this.queryParams.brandIds.length > 0) {
        getSeriesName(this.queryParams.brandIds).then((res) => {
          this.seriesList = res;
        });
      } else {
        this.queryParams.seriesIds = [];
        this.queryParams.modelIds = [];
        this.modelList = [];
        this.seriesList = [];
      }
    },
    getModelName() {
      if (this.queryParams.seriesIds.length > 0) {
        getModelName(this.queryParams.seriesIds).then((res) => {
          this.modelList = res;
        });
      } else {
        this.queryParams.modelIds = [];
        this.modelList = [];
      }
    },
    sure() {
      this.multipleSelectionSeries = this.multipleSelectionSeries?.filter(item => item !== null)
      this.multipleSelectionModel = this.multipleSelectionModel?.filter(item => item !== null)
      let data = {
        quotationProductSchemeId: this.$route.query.id,
        matchingRelation: this.vicType,
        brandIds: this.multipleSelectionBrand,
        seriesIds: this.multipleSelectionSeries?.map(item => (item.split("_").pop())),
        modelIds: this.multipleSelectionModel?.map(item => (item.split("_").pop())),
        modelType: this.typeRadio,
      };
      const loading = this.$loading({
        lock: true,
        text: "保存中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // 如果是新增进来的走 addCarModel接口
      if (this.$route.query.type == 'add') {
        addCarModel(data).then((res) => {
          loading.close();
          this.$message({
            type: "success",
            message: "选择车型成功",
          });
          this.$router.push({
            name: "ProductScheme",
          });
        })
          .catch((err) => {
            loading.close();
          });
      } else {
        // 如果是编辑进来的走 updateCarModel接口
        updateCarModel(data)
          .then((res) => {
            loading.close();
            this.$message({
              type: "success",
              message: "编辑车型成功",
            });
            this.$router.push({
              name: "ProductScheme",
            });
          })
          .catch((err) => {
            loading.close();
          });
      }
    },
    back() {
      this.$tab.closeOpenPage(this.$route);
      if (this.$route.query.beForm == "ProductScheme") {
        this.$router.push({
          name: this.$route.query.beForm,
        });
      } else {
        this.$router.push({
          name: this.$route.query.beForm,
          query: {
            id: this.$route.query && this.$route.query.id,
            beForm: this.$route.query.beForm,
            type: this.$route.query.type,
          },
        });
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      (this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }),
        (this.seriesList = []);
      this.brandList = [];
      this.seriesList = [];
      this.modelList = [];
      this.multipleSelectionBrand = []
      this.multipleSelectionSeries = []
      this.multipleSelectionModel = []
      // this.typeRadio = 1
      this.$refs['el-table'].table_clearSelection()
      this.getName()
      if (this.$route.query.type == "add" || this.$route.query.type == "edit") {
        this.getList();
      } else {
        this.getModelCar();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.$route.query.type == "add" || this.$route.query.type == "edit") {
        this.getList();
      } else {
        this.getModelCar();
      }
    },
    // 全选字段
    handleSelectionChange(val) {
      if (this.typeRadio == 1) {
        let multipleSelectionBrand = val.map((item) => item.indexId);
        // if (this.multipleSelectionSeries) {
        //   this.multipleSelectionBrand = multipleSelectionBrand.filter(element => !this.multipleSelectionSeries.includes(element));
        // }
        // if (this.multipleSelectionModel) {
        //   this.multipleSelectionBrand = multipleSelectionBrand.filter(element => !this.multipleSelectionModel.includes(element));
        // }
        // if (this.multipleSelectionModel && this.multipleSelectionSeries) {
        this.multipleSelectionBrand = [...new Set([...multipleSelectionBrand].filter(element => !this.multipleSelectionSeries?.includes(element) && !this?.multipleSelectionModel.includes(element)))];
        // }
      } else if (this.typeRadio == 2) {
        let multipleSelectionSeries = val.map((item) => item.indexId);
        // if (this.multipleSelectionBrand) {
        //   this.multipleSelectionSeries = multipleSelectionSeries.filter(element => !this.multipleSelectionBrand.includes(element));
        // }
        // if (this.multipleSelectionModel) {
        //   this.multipleSelectionSeries = multipleSelectionSeries.filter(element => !this.multipleSelectionModel.includes(element));
        // }
        // if (this.multipleSelectionModel && this.multipleSelectionBrand) {
        this.multipleSelectionSeries = [...new Set([...multipleSelectionSeries].filter(element => !this.multipleSelectionBrand?.includes(element) && !this?.multipleSelectionModel.includes(element)))];
        // }
      } else {
        let multipleSelectionModel = val.map((item) => item.indexId);
        this.multipleSelectionModel = [...new Set([...multipleSelectionModel].filter(element => !this.multipleSelectionBrand?.includes(element) && !this?.multipleSelectionSeries.includes(element)))];
      }
    },
    /** 查询测试单表列表 新增或者编辑调取接口*/
    getList() {
      this.loading = true;
      this.queryParams = {
        ...this.queryParams,
        modelType: this.typeRadio
      }
      getQueryModelByIdList(this.queryParams).then((res) => {
        if (res.code == "200") {
          const { rows, total } = res;
          if (this.typeRadio == 1) {
            this.brandDataList = rows;
          } else if (this.typeRadio == 2) {
            this.seriesDataList = rows;
          } else {
            this.modelDataList = rows;
          }
          this.listDataS = rows
          this.total = total;
          this.loading = false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
